//
//  SpotDetailViewController.m
//  SXH
//
//  Created by 房 国生 on 15/6/25.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "SpotDetailViewController.h"
#import "CommonService.h"
#import "UIImageView+WebCache.h"
#import "SpotPopTableViewCell.h"
#import "MBProgressHUD.h"
#import "YYAnimationIndicator.h"
#import "UIImageView+LK.h"
#import "AppDelegate.h"
#import "JT3DScrollView.h"
#import "SpotViewController.h"
#import "AFSoundManager.h"
#import "UIImage+ImageEffects.h"
#import "SDWebImageManager.h"
#import <MediaPlayer/MediaPlayer.h>
#import "JDStatusBarNotification.h"
#import "UserEntity.h"
#import "AppDelegate.h"
#import "GXPlayView.h"
#import "SVProgressHUD.h"
static NSInteger num = 2000;
static NSInteger park_musicId = 2000;

@interface SpotDetailViewController ()<UIGestureRecognizerDelegate, MBProgressHUDDelegate,UITextViewDelegate> {
    MBProgressHUD *HUD;
    NSString *spot_path;
   
    double durationTime;
    double finalTime;
    double isSame;
   
    
}
@property (weak, nonatomic) IBOutlet UIView *controlView;
@property (weak, nonatomic) IBOutlet UIView *photoView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightScroll;
@property (nonatomic, strong) NSMutableArray *mutableArrayImageView;
@property (nonatomic, strong) IBOutlet UILabel *labelTitle;
@property (weak, nonatomic) IBOutlet UIImageView *bg_spot_img;
@property (weak, nonatomic) IBOutlet UIImageView *bg_listView_img;
@property (nonatomic, strong) JT3DScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *aboveBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (nonatomic,assign) BOOL isTabel;
@property (weak, nonatomic) IBOutlet UIButton *btnCircle;
@end
static NSString *const SBStyle2 = @"SBStyle2";
@implementation SpotDetailViewController

@synthesize soundSlider, progressSlider, playBtn, circleBtn, currentTimeLabel, totalTimeLabel, musicTableView, lrcTableView;
@synthesize textViewContent;
@synthesize entity, mutableArrayImageView;
@synthesize tableViewSpot, viewListSpot;
@synthesize labelListTitle, labelTitle;
@synthesize musicArrayNumber, parkEntity, musicArray,isPlay,currentSpot,reStart,isAppear;
-(void)playMusicProgress:(ProgressValueBlock)progressValueBlock finshBlock:(FinshBlock)finsh nextBlock:(NextBlock)nextBlock
{
    _finshblock = finsh;
    _progressValueBlock = progressValueBlock;
    _nextBlock = nextBlock;
}
-(void)pauseImage:(PauseBlock )pauseBlock resume:(ResumeBlock)resumeBlock
{
    _pauseBlock = pauseBlock;
    _resumeBlock = resumeBlock;
}
+(instancetype)sharedInstance {
    
    static SpotDetailViewController *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
        [JDStatusBarNotification addStyleNamed:SBStyle2
                                       prepare:^JDStatusBarStyle *(JDStatusBarStyle *style) {
                                           style.barColor = [UIColor colorWithRed:0.365 green:0.800 blue:0.271 alpha:1.00];
                                           style.textColor = [UIColor whiteColor];
                                           style.animationType = JDStatusBarAnimationTypeBounce;
                                           if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
                                               style.font = [UIFont fontWithName:@"DINCondensed-Bold" size:15.0];
                                               style.textVerticalPositionAdjustment = 2.0;
                                        
                                           } else {
                                               style.font = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:15.0];
                                           }
                                           return style;
                                       }];

    });
    
    return instance;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.labelTitle.text = entity.title;
    self.scrollView = [[JT3DScrollView alloc]initWithFrame:CGRectMake(0, 62, SCREEN_WIDTH, SCREEN_WIDTH*142/320)];
    self.scrollView.clipsToBounds = YES;
    self.isTabel = NO;
    isSame = NO;
    isCircle = YES;
    lrcLineNumber = 0;
    musicTableViewHidden = YES;//初始化隐藏歌曲目录
    musicTableView.hidden = YES;
//    [AFSoundManager sharedManager].delegate = self;
    //初始化要加载的曲目
    
    
    if (musicArray == nil) {
        
        [self initDate];
        musicArrayNumber = 0;
    } else {
        NSString *str = [NSString stringWithFormat:@"景点播放列表(%lu)首", (unsigned long)[musicArray count]];
        labelListTitle.text = str;
    }
    
    //初始化音量和音量进度条
    soundSlider.value = 0.1;
    [soundSlider setThumbImage:[UIImage imageNamed:@"导览_10@2x.png"] forState:UIControlStateNormal];
    [soundSlider setThumbImage:[UIImage imageNamed:@"导览_10@2x.png"] forState:UIControlStateHighlighted];
    //    soundSlider.hidden = YES;
    
    //初始化歌词词典
    timeArray = [[NSMutableArray alloc] initWithCapacity:10];
    LRCDictionary = [[NSMutableDictionary alloc] initWithCapacity:10];
    
    //初始化播放进度条
    [progressSlider setThumbImage:[UIImage imageNamed:@"导览_10@2x.png"] forState:UIControlStateNormal];
    [progressSlider setThumbImage:[UIImage imageNamed:@"导览_10@2x.png"] forState:UIControlStateHighlighted];
    [progressSlider setMinimumTrackTintColor:[UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1]];
    [progressSlider addTarget:self action:@selector(backOrForwardAudio:) forControlEvents:UIControlEventValueChanged];
    progressSlider.value = 0;
    
    NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
    NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID];
    NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
    spot_path = [park_path stringByAppendingPathComponent:@"audio"];
    textViewContent.layoutManager.allowsNonContiguousLayout = NO;
    
    //后台播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    
    

    textViewContent.text = entity.content;

   
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineHeightMultiple = 1.5;
    paragraphStyle.maximumLineHeight = 25.f;
    paragraphStyle.minimumLineHeight = 15.f;
    paragraphStyle.firstLineHeadIndent = 40.f;
    paragraphStyle.alignment = NSTextAlignmentJustified;
    paragraphStyle.lineSpacing = 2;// 字体的行间距
    paragraphStyle.headIndent = 10;
    paragraphStyle.tailIndent = -10;
    NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSParagraphStyleAttributeName:paragraphStyle, NSForegroundColorAttributeName:[UIColor whiteColor]
                                  };
    self.textViewContent.attributedText = [[NSAttributedString alloc]initWithString:self.textViewContent.text attributes:attributes];
    self.textViewContent.delegate = self;
    //设置监控 每秒刷新一次时间
    
    tableViewSpot.tag = 3;
    [self.view addSubview:viewListSpot];
    [self.viewListSpot setFrame:CGRectMake(0, ScreenHeight,ScreenWidth, viewListSpot.frame.size.height)];
    
    //[self animeData];

    self.scrollView.effect = JT3DScrollViewEffectDepth;
    self.scrollView.delegate = self; // Use only for animate nextButton and previousButton
//    
//    if (firstView) {
//        [self hideFirstView];
//    }
    [self.view addSubview:self.scrollView];
    _heightScroll.constant = 61+SCREEN_WIDTH*142/320;
    

    self.bg_spot_img.contentMode = UIViewContentModeScaleAspectFill;
    self.bg_spot_img.clipsToBounds = YES;

}

#pragma mark 载入歌曲数组
- (void)initDate {
    musicArray = [[NSMutableArray alloc]init];
}

#pragma mark 播放目前的音乐
- (IBAction)play:(id)sender {
    if (reStart) {
        [self updatePlayerSetting];
    }else{
        if (_isPause) {
            [self resumeAudio];
            if (_resumeBlock) {
                _resumeBlock();
            }
            
            [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_23.png"] forState:UIControlStateNormal];
            _isPause = NO;
        } else {
            _isPause = YES;
            [self pauseAudio];
            if (_pauseBlock) {
                _pauseBlock();
            }
            
            [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_18.png"] forState:UIControlStateNormal];
            DebugLog(@"===================pause");
        }
        audioPlayer.volume = soundSlider.value;//重置音量,(每次播放的默认音量好像是1.0)
    }
}
//后台播放控制
-(void)pauseMusic
{
     [self pauseAudio];
     [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_18.png"] forState:UIControlStateNormal];
//    isPlay = NO;
    DebugLog(@"pause=========");
}
-(void)playMusic
{
    DebugLog(@"resumeAudio=========");
    [self updateTime];
    [self resumeAudio];
    [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_23.png"] forState:UIControlStateNormal];
    isPlay = YES;
}
#pragma mark 上一首
- (IBAction)aboveMusic:(id)sender {
    if (musicArrayNumber == 0) {
        musicArrayNumber = musicArray.count;
    }
    musicArrayNumber --;
    
    [self initMainView];
}
#pragma mark 下一首
- (IBAction)nextMusic:(id)sender {
    if (musicArrayNumber == musicArray.count - 1) {
        musicArrayNumber = -1;
    }
    DebugLog(@"nextMusic=========");
    musicArrayNumber ++;
    if (_nextBlock) {
        _nextBlock(musicArray[musicArrayNumber]);
    }
    [self initMainView];
}
#pragma mark 自动进入下一首
//- (void)autoPlay {
//    //判断是否允许循环播放
//    if (isCircle == YES) {
//        if (musicArrayNumber == musicArray.count - 1) {
//            musicArrayNumber = -1;
//        }
//        musicArrayNumber ++;
//        [self updatePlayerSetting];
//    } else {
//        [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_18.png"] forState:UIControlStateNormal];
//        isPlay = NO;
//    }
//}

#pragma mark 摇一摇 换歌
- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion == UIEventSubtypeMotionShake) {
        if (musicArrayNumber == musicArray.count - 1) {
            musicArrayNumber = -1;
        }
        musicArrayNumber ++;
        [self updatePlayerSetting];
    }
}

//更新播放器设置
- (void)updatePlayerSetting {
    _isPause = NO;
     isSame = NO;
    reStart = NO;
    progressSlider.value = 0;
    //更新播放按钮状态
    [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_23.png"] forState:UIControlStateNormal];
    isPlay = YES;
    currentSpot = musicArray[musicArrayNumber];
    //更新曲目
    SpotEntity *entityTemp = [musicArray objectAtIndex:musicArrayNumber];
//    if ([AppDelegate instance].spot_from_local == YES) {
    
        DebugLog(@"[musicArray[musicArrayNumber] name] = %@", [musicArray[musicArrayNumber] audio]);
         NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:spot_path]) {
            NSString *localAudioPath = [CommonService addLocalRootPath:entityTemp.audio ParkId:parkEntity.ID];
            [self playLocalFile:localAudioPath];
            
        } else {
            [self playRemoteFile:entity.audio];
        }
//    } else {
//        [self playRemoteFile:entity.audio];
//    }
    
    
    //更新音量
    audioPlayer.volume = soundSlider.value;
    //重新载入歌词词典
}

- (IBAction)soundChange:(id)sender {
    audioPlayer.volume = soundSlider.value;
}

//- (IBAction)circle:(id)sender {
//    if (isCircle) {
//        circleBtn.alpha = 0.5;
//        isCircle = NO;
//    } else {
//        circleBtn.alpha = 1.0;
//        isCircle = YES;
//    }
//}

//选中后的响应函数
- (void)playTable:(NSUInteger)tableNumber {
    musicArrayNumber = tableNumber;
    [self updatePlayerSetting];
}

#pragma mark 歌曲目录 按钮
- (IBAction)rightView:(id)sender {
//    RightMenuViewController *rightView = [[RightMenuViewController alloc] init];
//    rightView.myMusic = self;
//    rightView.semiTitleLabel.text = @"";
//    self.rightSemiViewController = rightView;
//    rightView.view.frame = CGRectMake(0, 54, 320, 410);
}
//-----------------------------------------------------------------

#pragma mark 表视图
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 3) {
        return [musicArray count];
    } else {
        return [timeArray count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView.tag == 3) {
        static NSString *couponTableViewCellIdentifier=@"SpotPopTableViewCell";
        SpotPopTableViewCell *cell = (SpotPopTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SpotPopTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//该表格选中后没有颜色
        cell.backgroundColor = [UIColor clearColor];//[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];

        SpotEntity *spot_entity = [musicArray objectAtIndex:indexPath.row];
        cell.labelName.text = spot_entity.title;
        
        if ([AppDelegate instance].file_from_local == YES) {
            NSString *localImagePath = [CommonService addLocalRootPath:spot_entity.album ParkId:parkEntity.ID];
            DebugLog(@"%@", localImagePath);
            UIImage* img = [UIImage imageWithContentsOfFile:localImagePath];
            cell.imageViewIcon.image = img;
        } else {
            [cell.imageViewIcon sd_setImageWithURL:[NSURL URLWithString:spot_entity.album]];
        }
        [cell.imageViewIcon.layer setMasksToBounds:YES];
        [cell.imageViewIcon.layer setCornerRadius:2.0]; //设置矩形四个圆角半径
        
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        
        if ([entity.ID isEqualToString:spot_entity.ID] == YES) {
            cell.imageViewPlay.hidden = NO;
            cell.imageViewPlay.image = [UIImage imageNamed:@"导览列表_02"];
            [cell.labelName setTextColor:[UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1]];
        } else {
            cell.imageViewPlay.hidden = YES;
            [cell.labelName setTextColor:[UIColor whiteColor]];
        }
        //        [cell.contentView addSubview:lable];//往列表视图里加 label视图，然后自行布局
        return cell;
    } else {
        static NSString *cellIdentifier = @"LRCCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//该表格选中后没有颜色
        cell.backgroundColor = [UIColor clearColor];
        if (indexPath.row == lrcLineNumber) {
            cell.textLabel.text = LRCDictionary[timeArray[indexPath.row]];
            cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1.0];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
        } else {
            cell.textLabel.text = LRCDictionary[timeArray[indexPath.row]];
            cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
            cell.textLabel.font = [UIFont systemFontOfSize:13];
        }
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        return cell;
    }
}

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 3) {
        return 50;
    } else {
        return 35;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    entity = [musicArray objectAtIndex:indexPath.row];
    musicArrayNumber = indexPath.row;
    
    [tableViewSpot reloadData];
    
    [self initMainView];
    
    [self hidenPopMenu];
}

- (IBAction)animeData : (id)sender{
    
    //self.userInteractionEnabled = YES;
    self.isTabel = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedCancel:)];
    [self.view addGestureRecognizer:tapGesture];
    tapGesture.delegate = self;
    self.viewListSpot.backgroundColor = RGBACOLOR(0, 0, 0, .9);
    self.viewListSpot.alpha = 0.6;
    UIImage *image_shot = [self rn_screenshot];
    [UIView animateWithDuration:.35 animations:^{
        
        [self.viewListSpot setFrame:CGRectMake(self.viewListSpot.frame.origin.x, ScreenHeight-self.viewListSpot.frame.size.height, self.viewListSpot.frame.size.width, self.viewListSpot.frame.size.height)];
        self.viewListSpot.alpha = 1;
        self.viewListSpot.backgroundColor = [UIColor clearColor];
        self.bg_listView_img.image = [image_shot applyBlurWithRadius:10 tintColor:[UIColor colorWithWhite:0.2 alpha:0.6] saturationDeltaFactor:1.8 maskImage:nil];

    } completion:^(BOOL finished) {
        
    }];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if([touch.view isKindOfClass:[self class]]){
        return YES;
    }
    return NO;
}

- (IBAction)tappedCancel: (id)sender {
    [self hidenPopMenu];
}

- (void)hidenPopMenu {
    self.isTabel = NO;
    [UIView animateWithDuration:.35 animations:^{
        [self.viewListSpot setFrame:CGRectMake(0, ScreenHeight,ScreenWidth, viewListSpot.frame.size.height)];
        self.viewListSpot.alpha = 0;
    } completion:^(BOOL finished) {
        if (finished) {
            //[self.viewListSpot removeFromSuperview];
        }
    }];
}

- (void) initMainView {
    isPlay = YES;
    num = musicArrayNumber;
    park_musicId = [parkEntity.ID integerValue];
    entity = [musicArray objectAtIndex:musicArrayNumber];
    
    textViewContent.text = entity.content;
    labelTitle.text = entity.title;

    [self.scrollView loadPageIndex:musicArrayNumber animated:YES];
    [self.tableViewSpot reloadData];
    if ([mutableArrayImageView count] !=0) {
        UIImageView *bgimgview = [mutableArrayImageView objectAtIndex:musicArrayNumber];
         self.bg_spot_img.image = [bgimgview.image applyBlurWithRadius:10 tintColor:[UIColor colorWithWhite:0.2 alpha:0.6] saturationDeltaFactor:1.8 maskImage:nil];
    }
    
   
    [self performSelector:@selector(updatePlayerSetting) withObject:nil afterDelay:0.0f];
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self hidenPopMenu];
}


///-----------------------------------------------------------------------------------------------------------------------

-(void)playLocalFile:(NSString *)mp3Path {
    DebugLog(@"playlocalmusic=====");
    
    __weak __typeof(self)weakSelf  = self;
    [self stopAudio];
    isPlay = YES;
    [[AFSoundManager sharedManager]startPlayingLocalFileWithName:mp3Path andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
        if (!error) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"mm:ss"];
            
            NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSince1970:elapsedTime];
            currentTimeLabel.text = [formatter stringFromDate:elapsedTimeDate];
            if (timeRemaining < 0) {
                timeRemaining = 0;
            }
            NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
            totalTimeLabel.text = [formatter stringFromDate:timeRemainingDate];
            
            durationTime = elapsedTime;
            finalTime = timeRemaining+elapsedTime;
            if (finalTime != 0)
            {
                if (!isSame) {
                    [weakSelf changeProgress];
                }
            }
            if (elapsedTime==0 &&timeRemaining ==0) {}else{
                progressSlider.value = elapsedTime/(timeRemaining+elapsedTime);
                if (_progressValueBlock ) {
                    self.progressValueBlock(elapsedTime/(timeRemaining+elapsedTime));
                }
                
                DebugLog(@"%f",progressSlider.value);
                if (elapsedTime/(timeRemaining+elapsedTime) == 1) {
                    [self stopAudio];
                    if (_finshblock) {
                        _finshblock();
                        DebugLog(@"finsh=========");
                    }
                    
                    
                    
                    progressSlider.value = 0;
                    if (!_autoPlayFunction) {
                        if ([UserEntity sharedInstance].isCircle) {
                            reStart = NO;
                            
                            [weakSelf nextMusic:_nextBtn];
                            if (!isAppear ) {
                                [JDStatusBarNotification showWithStatus:[NSString stringWithFormat:@"正在播放：%@",entity.title] styleName:SBStyle2];
                            }
                            
                        }else{
                            
                            [JDStatusBarNotification dismissAnimated:YES];
                            [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_18.png"] forState:UIControlStateNormal];
                            _isPause = YES;
                            reStart = YES;
                        }
                        
                    }else{
                        
                        [JDStatusBarNotification dismissAnimated:YES];
                        [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_18.png"] forState:UIControlStateNormal];
                        _isPause = YES;
                        reStart = YES;
                    }
                    
                }
            }
        } else {
            
            NSLog(@"There has been an error playing the remote file: %@", [error description]);
        }
    }];
    
    [self configNowPlayingInfoCenter];
}


-(void)playRemoteFile:(NSString *)url {
    DebugLog(@"playRemotemusic=====url=%@",url);
    __weak __typeof(self)weakSelf  = self;
    [self stopAudio];
     isPlay = YES;
    [[AFSoundManager sharedManager]startStreamingRemoteAudioFromURL:url andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
        
        if (!error) {
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"mm:ss"];
            
            NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSince1970:elapsedTime];
            currentTimeLabel.text = [formatter stringFromDate:elapsedTimeDate];
            if (timeRemaining < 0) {
                timeRemaining = 0;
            }
            NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
            totalTimeLabel.text = [formatter stringFromDate:timeRemainingDate];
            durationTime = elapsedTime;
            finalTime = timeRemaining+elapsedTime;
            if (finalTime != 0)
            {
                if (!isSame) {
                    [weakSelf changeProgress];
                    
                }
            }
            if (elapsedTime==0 &&timeRemaining ==0) {}else{
                progressSlider.value = elapsedTime/(timeRemaining+elapsedTime);
                if (_progressValueBlock) {
                    _progressValueBlock(elapsedTime/(timeRemaining+elapsedTime));
                }
                
                DebugLog(@"================%f",elapsedTime/(timeRemaining+elapsedTime));
                if (elapsedTime/(timeRemaining+elapsedTime) == 1) {
                    [self stopAudio];
                    if (_finshblock) {
                        _finshblock();
                    }
                    
                    progressSlider.value = 0;
                    if (!_autoPlayFunction) {
                        if ([UserEntity sharedInstance].isCircle) {
                            reStart = NO;
                            [weakSelf nextMusic:_nextBtn];
                            if (!isAppear) {
                                [JDStatusBarNotification showWithStatus:[NSString stringWithFormat:@"正在播放：%@",entity.title] styleName:SBStyle2];
                            }
                            
                        }else{
                            
                            [JDStatusBarNotification dismissAnimated:YES];
                            [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_18.png"] forState:UIControlStateNormal];
                            _isPause = YES;
                            reStart = YES;
                        }
                        
                    }else{
                        
                        [JDStatusBarNotification dismissAnimated:YES];
                        [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_18.png"] forState:UIControlStateNormal];
                        _isPause = YES;
                        reStart = YES;
                    }
                }
            }
        } else {
            
            NSLog(@"There has been an error playing the remote file: %@", [error description]);
        }
        
        
    }];
    [self configNowPlayingInfoCenter];
 
}

-(void)backOrForwardAudio:(UISlider *)sender {
    
    [[AFSoundManager sharedManager]moveToSection:sender.value];
}

-(void)pauseAudio {

    _isPause = YES;
    [self updateTime];
    [[AFSoundManager sharedManager]pause];
    
}

-(void)resumeAudio {
    _isPause = NO;
    [[AFSoundManager sharedManager]resume];
}
-(void)stopAudio
{
    isPlay = NO;
    [[AFSoundManager sharedManager]stop];
}
- (IBAction)doBack:(id)sender {

    for (int i = 0; i < [mutableArrayImageView count]; i++) {
        if (i != musicArrayNumber)
        {
            UIImageView *imageView = [mutableArrayImageView objectAtIndex:i];
            imageView.image = nil;
        }
        else
        {
            UIImageView *imageView = [mutableArrayImageView objectAtIndex:i];
            [imageView performSelector:@selector(setImage:) withObject:nil afterDelay:0.3];
        }
    }
    [mutableArrayImageView removeAllObjects];
    //{{将image内存释放掉
    
    if (_isTap) {
        _isTap = NO;
        
        [UIView animateWithDuration:0.3 animations:^{
            self.view.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        } completion:^(BOOL finished){
             [self.view removeFromSuperview];
        }];
       
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
///-----------------------------------------------------------------------------------------------------------------------

- (void)createCard {
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = SCREEN_WIDTH*142/320;
    for (UIView *subview in self.scrollView.subviews) {
        if(subview.tag == 10) {
            [subview removeFromSuperview];
        }
        
    }
    for (int i = 0; i < [musicArray count]; i++) {
        SpotEntity *spot_entity = [musicArray objectAtIndex:i];
        CGFloat x = self.scrollView.subviews.count * SCREEN_WIDTH;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, 0, SCREEN_WIDTH, height)];
        imageView.layer.cornerRadius = 8.;
        imageView.tag =10;
        if ([AppDelegate instance].file_from_local == YES) {
            NSString *localImagePath = [CommonService addLocalRootPath:spot_entity.album1 ParkId:parkEntity.ID];
            DebugLog(@"%@", localImagePath);
            UIImage* img = [UIImage imageWithContentsOfFile:localImagePath];
            [imageView setImage:img];
        } else {
            imageView.imageURL = [NSURL URLWithString:spot_entity.album1];
        }
        
        [mutableArrayImageView addObject:imageView];
        
        [self.scrollView addSubview:imageView];
        self.scrollView.contentSize = CGSizeMake(x + width, height);
        //        if (i == musicArrayNumber)
        //        {
        //            self.bg_spot_img.image = [imageView.image applyBlurWithRadius:5 tintColor:[UIColor colorWithWhite:0.4 alpha:0.2] saturationDeltaFactor:1.8 maskImage:nil];
        //        }
    }
    
    [self.scrollView setContentOffset:CGPointMake(width*musicArrayNumber, 0)];
    if (musicArrayNumber != num || park_musicId != [parkEntity.ID integerValue]) {
        [self initMainView];
    }
}

#pragma mark - Next / Previous buttons

- (IBAction)loadNextPage:(id)sender
{
    [self.scrollView loadNextPage:YES];
}

- (IBAction)loadPreviousPage:(id)sender
{
    [self.scrollView loadPreviousPage:YES];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    /**
     *  如果是textview滚动就直接返回 2016.8.9-朱伟
     */
    if ([scrollView isKindOfClass:[UITextView class]]) {
        return;
    }
    if (musicArrayNumber == 0) {
        musicArrayNumber = musicArray.count;
    }
    musicArrayNumber = self.scrollView.currentPage;
    if (![scrollView isKindOfClass:[tableViewSpot class]]) {
        [self initMainView];
    }
    
}

- (IBAction)shareSpot:(id)sender {
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.delegate = self;
    HUD.labelText = Loading_Hard_Text;
    
    UIImageView *imageView = [mutableArrayImageView objectAtIndex:self.scrollView.currentPage];
    NSArray* imageArray = [[NSArray alloc] initWithObjects:imageView.image, nil];
    SpotEntity *spot_entity = [musicArray objectAtIndex:self.scrollView.currentPage];
    
    NSString *title = [NSString stringWithFormat:@"%@-%@", parkEntity.title, entity.title];
    [CommonService showShareActionSheet:self.view HUD:HUD
                             ImageArray:imageArray
                                    URL:PORTAL_URL
                                  Title:title
                                Content:spot_entity.content];
}
- (void)viewWillAppear:(BOOL)animated
{
    [JDStatusBarNotification dismiss];
   
    [super viewWillAppear:animated];
    isAppear = YES;
    if ([UserEntity sharedInstance].isCircle) {
        [_btnCircle setBackgroundImage:[UIImage imageNamed:@"循环播放关"] forState:UIControlStateNormal];
    }else{
        [_btnCircle setBackgroundImage:[UIImage imageNamed:@"循环播放"] forState:UIControlStateNormal];
 
    }
    [MobClick beginLogPageView:@"SpotDetailViewController"];
    mutableArrayImageView = [[NSMutableArray alloc] init];
        [self createCard];
    if (_isPause) {
        [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_18.png"] forState:UIControlStateNormal];
    }else{
        [playBtn setBackgroundImage:[UIImage imageNamed:@"导览_23.png"] forState:UIControlStateNormal];
    }
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    isAppear = NO;
    if (!_isPause) {
        [JDStatusBarNotification showWithStatus:[NSString stringWithFormat:@"正在播放：%@",entity.title] styleName:SBStyle2];
    }
    [MobClick endLogPageView:@"SpotDetailViewController"];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
  
}
//后台播放
- (void)configNowPlayingInfoCenter {
    //    isSame = YES;
    entity = [musicArray objectAtIndex:musicArrayNumber];
    if ( entity  == nil) {
        return;
    }
    
    
    @autoreleasepool {
        
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        //歌曲名称
        [dict setObject:entity.title forKey:MPMediaItemPropertyTitle];
        
        //演唱者
        //        [dict setObject:[info ObjectNullForKey:@"author"] forKey:MPMediaItemPropertyArtist];
        
        //专辑名
        //[dict setObject:[info ObjectNullForKey:@"album"] forKey:MPMediaItemPropertyAlbumTitle];
        
        //专辑缩略图
        NSString *localImagePath = [CommonService addLocalRootPath:entity.album1 ParkId:parkEntity.ID];
        
        NSData * thumbData = [NSData dataWithContentsOfFile:localImagePath];
        
        if (thumbData != nil) {
            UIImage *image = [UIImage imageWithData:thumbData];
            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
            [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
        }else{
            // FIXME: 无图的时候，读取图
            
        }
        //音乐剩余时长
        //
        //        [dict setObject:[NSNumber numberWithDouble:finalTime] forKey:MPMediaItemPropertyPlaybackDuration]; //音乐当前已经播放时间
        //
        //        [dict setObject:[NSNumber numberWithDouble:0.0] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
        //设置锁屏状态下屏幕显示播放音乐信息
        
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
        
    }
    

}
- (void)changeProgress{
    isSame = YES;
    //当前播放时间
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[[MPNowPlayingInfoCenter defaultCenter] nowPlayingInfo]];
    //        [dict setObject:[NSNumber numberWithDouble:CMTimeGetSeconds([AFSoundManager sharedManager].player.currentItem.currentTime)]forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime]; //音乐当前已经过时间
    [dict setObject:[NSNumber numberWithDouble:finalTime] forKey:MPMediaItemPropertyPlaybackDuration]; //音乐当前已经播放时间
    
    //    [dict setObject:[NSNumber numberWithDouble:0.0] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    
    
}
- (BOOL)canBecomeFirstResponder
{
    return YES;
}
-(void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlPlay:
                [self playMusic];
                break;
            case UIEventSubtypeRemoteControlPause:
                [self pauseMusic];
                break;
                
            case UIEventSubtypeRemoteControlPreviousTrack:
                [self aboveMusic:_aboveBtn];
                break;
                
            case UIEventSubtypeRemoteControlNextTrack:
                [self nextMusic:_nextBtn];
                break;
                
            default:
                break;  
        }  
    }  
}



- (UIImage *)rn_screenshot {
    UIGraphicsBeginImageContext(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT));
    if([self.view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]){
        [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:NO];
    }
    else{
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = image.CGImage;
    CGRect rect =CGRectMake(0, SCREEN_HEIGHT - 357, SCREEN_WIDTH, 357);//这里可以设置想要截图的区域
    CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
    UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
    NSData *imageData = UIImageJPEGRepresentation(sendImage, 0.75);
    image = [UIImage imageWithData:imageData];
    
    return image;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    return NO;
}

-(void)updateTime
{
    //当前播放时间
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[[MPNowPlayingInfoCenter defaultCenter] nowPlayingInfo]];
    [dict setObject:[NSNumber numberWithDouble:durationTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime]; //音乐当前已经播放时间
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
}
- (IBAction)circleAction:(id)sender {
    if ([UserEntity sharedInstance].isCircle) {
        [UserEntity sharedInstance].isCircle = NO;
        [SVProgressHUD showErrorWithStatus:@"循环播放功能关闭"];
        [[AppDelegate instance] saveUserEntity:[UserEntity sharedInstance]];
        [_btnCircle setBackgroundImage:[UIImage imageNamed:@"循环播放"] forState:UIControlStateNormal];
    }else{
        [UserEntity sharedInstance].isCircle = YES;
        [SVProgressHUD showSuccessWithStatus:@"循环播放功能开启"];
        [[AppDelegate instance] saveUserEntity:[UserEntity sharedInstance]];
        [_btnCircle setBackgroundImage:[UIImage imageNamed:@"循环播放关"] forState:UIControlStateNormal];
    }
    
}

@end



